package com.cyz.springdemo.Controller.elbai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cyz.springdemo.model.BaseResponse;
import com.cyz.springdemo.util.ErBaiSignUtil;
import com.cyz.springdemo.util.HttpRequestUtil;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springdemo
 * @description: 饿百接口测试控制器
 * @author: wangjie
 * @create: 2019-09-29 11:59
 **/
@RestController
@RequestMapping(value = "/ebai/Test")
public class ApiTestController {

    //商户秘钥
    private static final String secret = "77212d22d28e043d";
    private static final String source = "62737";

    /**
     * 商品列表
     */
    @RequestMapping(value = "/getSkuList" , method = RequestMethod.GET)
    public Object skuList(String shopId,Integer page) throws UnsupportedEncodingException {
        BaseResponse response = new BaseResponse();

        long timestamp = System.currentTimeMillis() / 1000;
        Gson gson = new Gson();

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("cmd","sku.list");
        params.put("encrypt","");
        params.put("secret",secret);
        params.put("source",source);
        params.put("ticket",ErBaiSignUtil.getTicket(String.valueOf(timestamp)));

        Map<String,Object> bodyParams = new HashMap<>();
        bodyParams.put("shop_id",shopId);
        bodyParams.put("page",page);

        params.put("body",bodyParams);
        params.put("version","3");
        params.put("timestamp",timestamp);

        String sign = ErBaiSignUtil.getSign(params);
        params.put("sign",sign);
        params.remove("secret");
        params.put("body", gson.toJson(params.get("body")));

        StringBuilder requestparams = new StringBuilder();
        for (Map.Entry<String, Object> map : params.entrySet()) {
            requestparams.append(map.getKey()+"="+map.getValue() + "&");
        }
        String requestParams = requestparams.substring(0, requestparams.length() - 1).toString();
        String result = HttpRequestUtil.sendPost("https://api-be.ele.me", requestParams);

        JSONObject jsonObject = JSON.parseObject(result);

        response.setData(jsonObject);
        return response;
    }

    @RequestMapping(value = "/getMd5")
    public String getMD5(String aaa){
        String md5="";
        try {
             md5 = ErBaiSignUtil.getMd5(aaa);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return md5.toUpperCase();
    }

}
